package region

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/enum/common"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateRegionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateRegionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateRegionLogic {
	return &BackendCreateRegionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Region management
func (l *BackendCreateRegionLogic) BackendCreateRegion(in *setting.RegionInfo) (*setting.BaseIDResp, error) {
	// get parent level
	var regionLevel uint8
	if in.ParentId != nil && *in.ParentId != common.DefaultParentId {
		p, err := l.svcCtx.SysRegion.FindOne(l.ctx, *in.ParentId)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		regionLevel = p.Level + 1
	} else {
		regionLevel = 1
	}

	var region model.SysRegion
	region.Level = regionLevel
	if in.ParentId != nil {
		region.ParentID = *in.ParentId
	}
	if in.Sort != nil {
		region.Sort = uint16(*in.Sort)
	} else {
		region.Sort = uint16(9999)
	}
	if in.Name != nil {
		region.Name = strings.TrimSpace(*in.Name)

		if len(region.Name) == 0 {
			logx.Errorw("create region failed, its name is required")
			return nil, errorx.NewInvalidArgumentError("region.nameRequired")
		}
	}
	if in.Code != nil {
		region.Code = strings.TrimSpace(*in.Code)

		if len(region.Code) == 0 {
			logx.Errorw("create region failed, its code is required")
			return nil, errorx.NewInvalidArgumentError("region.codeRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysRegionColumns.Code] = map[string][]any{
			"equalTo": []any{region.Code},
		}
		_, count, err := l.svcCtx.SysRegion.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("region.codeAlreadyExists")
		}
	}
	if in.Region != nil {
		region.Region = strings.TrimSpace(*in.Region)
	}
	if in.Status != nil {
		region.Status = uint8(*in.Status)
	} else {
		region.Status = uint8(globalkey.StatusEnabled)
	}
	region.CreatedAt = time.Now()
	region.UpdatedAt = time.Now()
	err := l.svcCtx.SysRegion.Insert(l.ctx, nil, &region)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseIDResp{
		Id:  region.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
